<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
class finance_ctl_shopscore extends desktop_controller{
    
    var $workground = 'finance_ctl_shopscore';
    var $pagelimit = 10;
    var $shopscore_model ;
    public function __construct($app)
    {
        parent::__construct($app);
        $this->spScoreMdl = $this->app->model('shopscore');
        header("cache-control: no-store, no-cache, must-revalidate");
    }
   function index(){
   	
        $custom_actions[] = array('label'=>app::get('finance')->_('添加'),'href'=>'index.php?app=finance&ctl=shopscore&act=add_page','target'=>'dialog::{title:\''.app::get('finance')->_('添加').'\',width:660,height:340}');
        $custom_actions[] = array('label'=>app::get('finance')->_('核算积分'),'submit'=>'index.php?app=finance&ctl=shopscore&act=calcscore');
        $custom_actions[] = array('label'=>app::get('finance')->_('取消核算'),'submit'=>'index.php?app=finance&ctl=shopscore&act=recalcscore');
        $custom_actions[] = array('label'=>app::get('finance')->_('过数'),'submit'=>'index.php?app=finance&ctl=shopscore&act=syncscore');

        $actions_base['title'] = app::get('finance')->_('抵扣积分');
        $actions_base['actions'] = $custom_actions;
        $actions_base['allow_detail_popup'] = true;
        $actions_base['use_buildin_set_tag'] = false;
        $actions_base['use_buildin_export'] = false;
        $actions_base['use_buildin_filter'] = false;

        $actions_base['use_view_tab'] = false;

        $this->finder('finance_mdl_shopscore',$actions_base);
    }
    function add_page()
    {

        $sql = "SELECT shop_id,shop_bn,name from sdb_ome_shop where leemantype='1' order by shop_bn ";
        $dly_corp_datas = kernel::database()->select($sql);
        $this->pagedata['dly_corp'] = $dly_corp_datas;
        $this->pagedata['pam_account']['operator']=kernel::single('desktop_user')->get_name();
        $this->display('shopscore/new.html');
    }
    /*
     * 生成调整单号
     *
     *
     * @return 退货单号
     */
    function gen_id(){
        $i = rand(0,9999);
        do{
            if(9999==$i){
                $i=0;
            }
            $i++;
            $sc_bn = date("YmdH").'13'.str_pad($i,6,'0',STR_PAD_LEFT);
            $row = kernel::database()->selectrow('select sc_bn from sdb_finance_shopscore where sc_bn =\''.$sc_bn.'\'');
        }while($row);
        return $sc_bn;
    }

    function add()
    {
        // 添加
        $this->begin();
        $shopscore_model = $this->app->model('shopscore');
        $id=$_POST['pam_account']['id'];
        $begin = strtotime($_POST['pam_account']['begin_date']);
        $end = strtotime($_POST['pam_account']['end_date'])+86399;
        if($begin>$end)
        {
            $this->end(false, app::get('base')->_('结束时间小于开始时间，请确认！'));
        } 
        $db = kernel::database();
        if(empty($id))
        {
            $sql="SELECT * from sdb_finance_shopscore where begin_date<=$begin and $begin<end_date and shop_id='".$_POST['pam_account']['shop_id']."'";
        }else{
            $sql="SELECT * from sdb_finance_shopscore where begin_date<=$begin and $begin<end_date and shop_id='".$_POST['pam_account']['shop_id']."' and id!='$id'";
        }
        $rows= $db->select($sql);
        if(!empty($rows))
        {
            $this->end(false, app::get('base')->_('开始时间已存在区间，请确认日期！'));
        }
        if(empty($id))
        {
            $sql1="SELECT * from sdb_finance_shopscore where begin_date<=$end and $end<end_date and shop_id='".$_POST['pam_account']['shop_id']."'";
        }else{
            $sql1="SELECT * from sdb_finance_shopscore where begin_date<=$end and $end<end_date and shop_id='".$_POST['pam_account']['shop_id']."' and id!='$id'";
        }
        $rows1= $db->select($sql1);
        if(!empty($rows1))
        {
            $this->end(false, app::get('base')->_('结束时间已存在区间，请确认日期！'));
        }
        if(empty($id))
        {
            $sql2="SELECT * from sdb_finance_shopscore where begin_date>=$begin and $end>=end_date and shop_id='".$_POST['pam_account']['shop_id']."'";
        }else{
            $sql2="SELECT * from sdb_finance_shopscore where begin_date>=$begin and $end>=end_date and shop_id='".$_POST['pam_account']['shop_id']."' and id!='$id'";
        }
        $rows2= $db->select($sql2);
        if(!empty($rows2))
        {
            $this->end(false, app::get('base')->_('该区间已重复定义，请确认日期！'));
        }
        $arr_order['pam_account']['shop_id'] = $_POST['pam_account']['shop_id'];
        $arr_order['pam_account']['begin_date'] = strtotime($_POST['pam_account']['begin_date']);
        $arr_order['pam_account']['end_date'] = strtotime($_POST['pam_account']['end_date'])+86399;
        $arr_order['pam_account']['booked_time'] = strtotime($_POST['pam_account']['booked_time']);
        $arr_order['pam_account']['operator'] = $_POST['pam_account']['operator'];
        $arr_order['pam_account']['remark'] = $_POST['pam_account']['remark'];
        $arr_order['pam_account']['src_customer'] = $_POST['pam_account']['src_customer'];
        $arr_order['pam_account']['create_time'] =time();
        $arr_order['pam_account']['operator'] =$_POST['pam_account']['operator'];
        if(empty($_POST['pam_account']['sc_bn']))
        {
            $arr_order['pam_account']['sc_bn'] =$this->gen_id();
        }else{
            $arr_order['pam_account']['sc_bn'] =$_POST['pam_account']['sc_bn'];
        }
        
        if($_POST)
        {
            if($_POST['pam_account']['id'] != '')
            {

                $db = kernel::database();
                $db->beginTransaction();
                if( $shopscore_model->update($arr_order['pam_account'], array('id' => $_POST['pam_account']['id'])) )
                {
                    $db->commit();
                }else{
                    $msg = '保存失败，请联系客服!';
                    return false;
                }
                $this->end(true, app::get('ome')->_('添加成功！'));
            } 
            else 
            {
                $db = kernel::database();
                $db->beginTransaction();
                if( $shopscore_model->save($arr_order['pam_account']) )
                {
                    $db->commit();
                }else{
                    $msg = '保存失败，请联系客服!';
                    return false;
                }
                $this->end(true, app::get('ome')->_('添加成功！'));
            }
        }
    }
    //核算积分
    function calcscore()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=finance&ctl=shopscore&act=index");
        $this->_request = kernel::single('base_component_request');
        $postData = $this->_request->get_post();
        if ($postData['isSelectedAll'] == '_ALL_') {
            $this->end(false, '不可全选！');
        }
        if (count($postData['id']) > 1) 
        {
            $this->end(false, '请单条核算！');
        }
        //add by ldward 20181128核算积分
        $id=$postData['id'][0];
        $spdocMdl = $this->app->model('shopscore');
        $spdocMdlL = $this->app->model('shopscore_line');
        $spdata=$spdocMdl->dump($id,"*");
        if($spdata['status']!='unconfirmed')
        {   
            $this->end(false, '状态异常，无法核算积分！');
        }

        $db=kernel::database();
        $db->exec("delete from sdb_finance_shopscore_line where shopscore_id=".$id);
        $sql="SELECT distinct f.AXCustomer,f.customername,d.axorderno,d.axshipno,os.score_u,os.order_bn,total_amount
             from sdb_wms_deliverycomp a 
             inner join sdb_wms_deliverycomp_line b on a.id = b.deliverycomp_id
             inner join sdb_wms_deliverynote_line d on b.deliverynote_id = d.deliverynote_id
             inner join sdb_wms_deliverynote  dn on dn.id=d.deliverynote_id
             inner join sdb_wms_delivery e on d.delivery_id = e.delivery_id
             inner join sdb_ome_shop f on e.shop_id = f.shop_id
             inner JOIN sdb_ome_delivery od on ( e.outer_delivery_bn = od.delivery_bn )
             inner JOIN sdb_ome_delivery_order odo on ( od.delivery_id = odo.delivery_id )
             inner JOIN sdb_ome_orders os on (odo.order_id = os.order_id)
        where a.deliverycomp_time between ".$spdata['begin_date']." and ".$spdata['end_date']." and f.shop_id='".$spdata['shop_id']."' and os.score_u>0";
        
        $res=$db->select($sql);
        $orderBns = array();
        foreach ($res as $key => $value) 
        {
            if(!in_array($value['order_bn'], $orderBns))
            {
                $arr_line='';
                $arr_line['shopscore_id']=$id;
                $arr_line['AXCustomer']=$value['AXCustomer'];
                $arr_line['customername']=$value['customername'];
                $arr_line['axorderno']=$value['axorderno'];
                $arr_line['axshipno']=$value['axshipno'];
                $arr_line['score']=$value['score_u'];
                $arr_line['order_bn']=$value['order_bn'];
                $arr_line['total_amount']=$value['total_amount'];
                $spdocMdlL->insert($arr_line);
                $orderBns[]=$value['order_bn'];
            }
        }
        $db->exec("update sdb_finance_shopscore set status='created',last_modify='".time()."' where id in(" . $id . ");"); 
        $this->end(true, '已完成');
    }
    function recalcscore()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=finance&ctl=shopscore&act=index");
        $this->_request = kernel::single('base_component_request');
        $postData = $this->_request->get_post();
        if ($postData['isSelectedAll'] == '_ALL_') {
            $this->end(false, '不可全选！');
        }
        if (count($postData['id']) > 1) 
        {
            $this->end(false, '请单条取消生成！');
        }
        //add by ldward 20181128生成明细
        $id=$postData['id'][0];
        $spdocMdl = $this->app->model('shopscore');
        $spdata=$spdocMdl->dump($id,"*");
        if($spdata['status']!='created')
        {   
            $this->end(false, '状态异常，无法取消生成！');
        }
        $db=kernel::database();
        $db->exec("delete from sdb_finance_shopscore_line  where  shopscore_id in(" . $id . ");");
        $db->exec("update sdb_finance_shopscore set status='unconfirmed',last_modify='".time()."' where  id in(" . $id . ");"); 
        $this->end(true, '取消成功！');
    }
    //过数积分
    function syncscore()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=finance&ctl=shopscore&act=index");
        $this->_request = kernel::single('base_component_request');
        $postData = $this->_request->get_post();
        if ($postData['isSelectedAll'] == '_ALL_') {
            $this->end(false, '不可全选！');
        }
        if (count($postData['id']) > 1) 
        {
            $this->end(false, '请单条同步！');
        }
        $id=$postData['id'][0];
        $spscoreMdl = $this->app->model('shopscore');
        $shopMdl =app::get('ome')->model('shop');
        $spscoreMdlL = $this->app->model('shopscore_line');

        $spscoredata=$spscoreMdl->dump($id,"*");
        $shopData=$shopMdl->dump($spscoredata['shop_id'],"*");
        $scoredataL=$spscoreMdlL->getList("*",array('shopscore_id' => $id ));
        if($spscoredata['status']!='created')
        {
            $this->end(false, '状态不为已生成，无法执行过数操作！');
        } 

        foreach ($scoredataL as $key => $value) 
        {
            $result[] =array(
                "CategoryId"=> "Sac040101",//默认给到AX积分对应的费用分类
                "CategoryName"=> "直通车推广费",
                "CustAccount"=> $shopData['AXCustomer'],
                "CustName"=> $shopData['AXCustomer'],
                "DescFlexfiled1"=> "",
                "DescFlexfiled2"=> "",
                "DescFlexfiled3"=> "",//费用项
                "DescFlexfiled4"=> $value['axorderno'],
                "DescFlexfiled5"=> $value['axshipno'],
                "ExpAmount"=>floatval($value['score']/100) ,
                "Key"=> $spscoredata['sc_bn'].$value['id'],
                "Posted"=> 0,
                "TransDate"=>date('Y-m-d h:i:s',$spscoredata['booked_time']),) ;
        }
        try 
        {
            date_default_timezone_set("PRC");
            ini_set('soap.wsdl_cache_enabled', "0"); //关闭wsdl缓存
            ini_set('default_socket_timeout', 500);
            $param['json'] = json_encode($result);//json
            $param['company'] = "1101";
            if(WITH_QIMEN){
                 $res=kernel::single('erpapi_rpc_qimen')->call('syncSalesIntegralDeduction',$param);
                 $arr = json_decode($res['response']['data'], '1');
            }else{               
                $webservice_url = "http://172.27.32.23:8089/AXToOMs.asmx?wsdl";
                $client = new SoapClient($webservice_url);
                $res = $client->__soapCall('syncSalesIntegralDeduction', array('parameters' => $param));
                $arr=json_decode($res->syncSalesIntegralDeductionResult,1);
            }
            if ($arr['Code']=='0') 
            {
                $data['status'] ='confirmed';
                $data['id'] = $id;
                app::get('finance')->model('shopscore')->save($data);
                $this->end(true, '同步成功');
            }elseif($arr['Code']=='99')
            {
                $this->end(false,$arr['Msg']);          
            }
        } catch (Exception $e) 
        {
            $this->end(false,$e->getMessage());   
        }
        $this->end(true, '同步成功');
    }


    function lmedit(){
        $shopscore = '';
        if(isset($_GET['id'])){
            $id = $_GET['id'];
            $shopscore_obj = kernel::single('finance_mdl_shopscore');
            $shopscore = $shopscore_obj->getList('*', array('id'=>$id), 0, 1);
        }

        $sql = "SELECT shop_id,shop_bn,name from sdb_ome_shop where leemantype='1' order by shop_bn ";
        $dly_corp_datas = kernel::database()->select($sql);
        $this->pagedata['dly_corp'] = $dly_corp_datas;
        $this->pagedata['pam_account'] = $shopscore[0];
        $this->pagedata['pam_account']['operator']=kernel::single('desktop_user')->get_name();
        $this->page('shopscore/new.html');

    }

    //理文测试
    
}
